<?php

namespace App\Kuafu\Shop\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\User\Model\User;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class ShopOperateTargetModel extends BaseModel
{
    use HasFactory, KfSoftDeletes, KfUid;

    protected $modelCached     = false;
    protected $table           = 'shop_operate_target';
    protected $primaryKey      = 'id';
    protected $fillable = [
        'shopId',
        'target',
        'brandId',
        'createdByUid',
        'updatedByUid'
    ];

    public function getCreatedAtAttribute()
    {
        return date('Y-m-d H:i:s', $this->attributes['createdAt']);
    }

    public function getUpdatedAtAttribute()
    {
        return date('Y-m-d H:i:s', $this->attributes['updatedAt']);
    }

    public function createdByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'createdByUid')->select('id', 'username');
    }

    public function updatedByUidRel()
    {
        return $this->hasOne(User::class, 'id', 'updatedByUid')->select(['id', 'username']);
    }

    /**
     * 新增运营目标
     * @param int $shopId
     * @param int $target
     * @param int $brandId
     * @return bool
     * @throws ShopException
     */
    public static function addData(int $shopId, int $target, int $brandId)
    {
        try {
            ShopOperateTargetModel::query()->create([
                'shopId'    => $shopId,
                'target'    => $target,
                'brandId'   => $brandId,
            ]);
            return true;
        } catch (\Exception $exception) {
            throw new ShopException(ShopCodeEnum::ERR_SHOP_NO_TARGET, '', $exception);
        }
    }

}
